Page({
  onLoad() {
    this.getHouseList()
  },
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    currentDate: Date.now(),
    houseId: '',
    name: '',
    gender: 1,
    houseList: [
      { name: '北京西三旗花园1号楼 101' },
      { name: '北京东村家园3号楼 302' },
      { name: '北京育新花园3号楼 703' },
      { name: '北京天通苑北苑8号楼 403' },
    ],
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },

  checkSelectHouse() {
    // 如果选择了房屋  houseId 就有值 没有选择就没有值
    const valid = Boolean(this.data.houseId)
    if (!valid) wx.utils.toast('请选择需要报修的房屋')
    return valid
  },

  checkName() {
    // 验证姓名的合法性
    const reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/
    const vaild = reg.test(this.data.name.trim())
    if (!vaild) wx.utils.toast('姓名必须是2~16的中文')
    return vaild
  },

  checkMobile() {
    // 定义正则
    const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
    const valid = reg.test(this.data.mobile)
    if (!valid) wx.utils.toast('请输入合法的手机号码')
    return valid
  },

  checkDate() {
    // 定义正则 日期的格式 2024-09-01   2024/09/01 需要校验这两个种格式
    const reg = /^\d{4}[-|/]\d{2}[-|/]\d{2}$/
    const valid = reg.test(this.data.visitDate)
    console.log(valid,22222)
    if (!valid) wx.utils.toast('请选择访问日期')
    return valid
  },

  async goPassport() {
    if (!this.checkSelectHouse()) return
    if (!this.checkName()) return
    if (!this.checkMobile()) return
    if (!this.checkDate()) return

    // 发送请求
    // console.log(this.data,11111)
    const {houseId, name, gender, mobile, visitDate} = this.data
    await wx.http.post('/visitor', {houseId, name, gender, mobile, visitDate})
    wx.utils.toast('新增访客成功')
    // 跳转页面
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index',
    })
  },
  selectHouse(e) {
    // console.log(e.detail)
    const { name: houseInfo, id: houseId  } = e.detail
    // console.log(houseId)
    this.setData({
      houseInfo,
      houseId
    })
  },
  selectDate(e) {
    // console.log(e)
    const time = e.detail
    // 需要将数据写入到 data 里面
    this.setData({
      visitDate: wx.utils.formatTime(time),
      dateLayerVisible: false
    })
  },
  async getHouseList() {
    const res = await wx.http.get('/house')
    // console.log(res)
    this.setData({
      houseList: res.data
    })
  }
})
